//获取token
var token = CoreUtil.getData("access_token");
//地址栏转义token中的#号
var tokenQuery = token.replace("#", "%23");
var tableIns1;
var table = layui.table;
var form = layui.form;
var layer = layui.layer;
var $ = jQuery = layui.jquery;
var laydate = layui.laydate;

var treetable;

var iconPicker;
var tree
var listData ;
layui.config({
    base: '/'
}).extend({
    treetable: 'treetable-lay/treetable',
    iconPicker: 'js/iconPicker'
}).use(['treetable', 'table', 'tree', "iconPicker"], function () {
    var reloadTreeTable = function () {
        // 获取商品类型
        CoreUtil.sendGet("/sysGoodsType/list", null, function (res) {
            if (!res.data) {
                renderTable([]);
            } else {
                listData = res.data
                renderTable(listData);
            }

        });
    }
    reloadTreeTable();

    treetable = layui.treetable;

    iconPicker = layui.iconPicker;
    var table = layui.table;
    tree = layui.tree;

    var renderTable = function (data) {
        treetable.render({
            // 渲染表格
            data: data
            , treeColIndex: 1
            , treeSpid: 0
            , treeIdName: 'id'
            , treePidName: 'pid'
            , treeDefaultClose: true
            , treeLinkage: false
            , elem: '#showTable'
            , page: false
            , toolbar: '#toolbar'
            , cols: [
                [
                    {type: 'numbers'}
                    , {field: "name", width: 150, title: '类型名称'}
                    , {field: "level", width: 90, title: '菜单等级'}
                    , {field: 'sort', width: 70, title: '排序'}
                    , {field: "updateTime", title: '修改时间'}
                    , {field: 'createTime', title: '创建时间'}
                    , {title: '操作', width: 180, toolbar: '#tool'}
                ]
            ]

        });
    }

    //表头工具
    table.on('toolbar(showTable)', function (obj) {
        switch (obj.event) {
            case 'batchDeleted':
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data;
                if (data.length == 0) {
                    layer.msg("请选择要批量删除的列");
                } else {
                    var ids = [];
                    $(data).each(function (index, item) {
                        ids.push(item.id);
                    });
                    tipDialog(ids);
                }
                break;
            case 'add':
                $(".table_div").hide();
                $(".operation").show();
                $(".title").html("添加");
                $(".operation input[name=id]").val("");
                $(".operation input[name=storeId]").val("");
                $(".operation input[name=name]").val("");
                $(".operation input[name=pid]").val("");
                $(".operation input[name=sort]").val("");
                $(".operation input[name=createTime]").val("");
                initTree();
                break;
        }
        ;
    });
    //列操作
    table.on('tool(showTable)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'del':
                var ids = [];
                ids.push(data.id);
                tipDialog(ids);
                break;
            case 'edit':
                $(".table_div").hide();
                $(".operation").show();
                $(".title").html("编辑");
                $(".operation input[name=id]").val(data.id);
                $(".operation input[name=storeId]").val(data.storeId);
                $(".operation input[name=name]").val(data.name);
                $(".operation input[name=pid]").val(data.pid);
                $(".operation input[name=sort]").val(data.sort);
                $(".operation input[name=createTime]").val(data.createTime);

                console.log(listData)
                console.log(listData.length)
                if(data.pid == 0){
                    $(".operation input[name=pidName]").val('默认顶级类型');

                }else{
                    for(var i = 0 ; i < listData.length; i++ ){
                        if(listData[i].id == data.pid){
                            $(".operation input[name=pidName]").val(listData[i].name);
                            console.log(listData[i].name);
                            break;
                        }
                    }
                }
                // 加载当前 类别一下的所有类型
                initTree(data);
                break;
        }
    });

    //删除
    var tipDialog = function (ids) {
        layer.open({
            content: "确定要删除么?",
            yes: function (index, layero) {
                layer.close(index); //如果设定了yes回调，需进行手工关闭
                CoreUtil.sendDelete("/sysGoodsType/delete", ids, function (res) {
                    layer.msg(res.msg, {time: 1000}, function () {
                        reloadTreeTable();
                    });
                });
            }
        });
    };

    //返回
    $("#btn_cancel").click(function () {
        $(".table_div").show();
        $(".operation").hide();
        return false;
    });

    //监听保存
    form.on('submit(submit)', function (data) {
        if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
            CoreUtil.sendPost("/sysGoodsType/add", data.field, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                reloadTreeTable();
            });
        } else {
            CoreUtil.sendPut("/sysGoodsType/update", data.field, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                reloadTreeTable();
            });
        }
        return false;
    });

    var initTree = function (data) {

        var param = {};
        if (data === undefined || data === null || data === "") {

        } else {
            param.goodsTypeId = data.id;
        }
        CoreUtil.sendGet("/sysGoodsType/terr", param, function (res) {
            tree.render({
                elem: '#menuTree'
                , data: res.data
                , id: 'typeId'
                , onlyIconControl: true  //是否仅允许节点左侧图标控制展开收缩
                , click: function (obj) {
                    selectNode = obj;
                    layer.msg(JSON.stringify(selectNode.data.title));
                }
            });
        });
    }
    // 选择类型
    $(".operation input[name=pidName]").click(function () {
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: "选择类型",
            area: ['400px', '450px'],
            shade: 0,
            shadeClose: false,
            content: jQuery("#menuTree"),
            btn: ['确定', '取消'],
            yes: function (index) {
                if (selectNode.data != null) {
                    $(".operation input[name=pid]").val(selectNode.data.id);
                    $(".operation input[name=pidName]").val(selectNode.data.title);
                }
                layer.close(index);
            }
        });
    });


});

//执行查询
function search() {
    //这里以搜索为例
    renderTable.reload({
        where: { //设定异步数据接口的额外参数，任意设
            key: $("#key").val()
        }
        , page: {
            curr: 1 //重新从第 1 页开始
        }
    });
};